package com.aphrodite.ui.widgets;

import java.util.Vector;

import javax.microedition.lcdui.Graphics;

//INCOMPLETE
public class LinkBar extends TraversableWidget {
	byte padding = 5;
	private int currentIndex;
	private int startIndex;
	private int endIndex;
	private Vector items = new Vector();

	public LinkBar(Theme theme, int width) {
		super(theme, width, 0);
		updateModel();
	}

	/**
	 * Add a link to the link bar
	 * 
	 * @param text
	 *            String representing the link
	 */
	public void addItem(String text) {
		items.addElement(text);
		updateModel();
	}

	public int getSelectedIndex() {
		return currentIndex;
	}

	public String getSelectedItem(int index) {
		return (String) items.elementAt(index);
	}

	public void render(Graphics g) {
		if (!isVisible)
			return;
		capture(g, width, height, true);
		int currX = 0;
		String tmp;
		for (int i = startIndex; i < endIndex; i++) {
			currX += padding;
			g.setColor(i == currentIndex ? theme.highLightColor : theme.fgColor);
			tmp = (String) items.elementAt(i);
			if (theme.bmFont == null) {
				g.setFont(theme.widgetFont);
				g.drawString(tmp, currX, 2, 0);
				currX += theme.widgetFont.stringWidth(tmp);
			} else {
				theme.bmFont.drawString(g, tmp, currX, 2, 0);
				currX += theme.bmFont.stringWidth(tmp);
			}
			currX += padding;
			/* draw Separator */
			g.setColor(theme.borderColor);
			g.drawLine(currX, 2, currX, height - 4);
			currX++;
		}
		release(g, width, height, true);
	}

	private int totalWidth;

	public final void resizeToFit() {
		width = totalWidth;
		startIndex = 0;
		endIndex = items.size();
	}

	public void setLinkPad(byte pad) {
		padding = pad;
	}

	protected void updateModel() {
		height = (theme.bmFont == null) ? theme.widgetFont.getHeight() : theme.bmFont.getHeight();
		/* Add padding */
		height += 4;
		endIndex = itemsCanFit();
		System.out.println("End index " + endIndex);
		reDrawWidget();
	}

	private int itemsCanFit() {
		int estateUsed = 0;
		String tmp;
		int itemTot = 0;
		int i = 0;
		for (i = 0; i < items.size(); i++) {
			estateUsed += padding;
			tmp = (String) items.elementAt(i);
			if (theme.bmFont == null) {
				estateUsed += theme.widgetFont.stringWidth(tmp);
			} else {
				estateUsed += theme.bmFont.stringWidth(tmp);
			}
			estateUsed += padding;
			estateUsed++;
			if (estateUsed >= width)
				itemTot = i;
		}
		totalWidth = estateUsed;
		return itemTot;
	}

	protected boolean traverse(int dir, int viewportWidth, int viewportHeight, int[] visRect_inout) {
		return false;
	}
}
